import React from 'react';
// 临时定义，避免导入错误
const R = {
  publics: {
    placeholder: () => 'https://via.placeholder.com/150',
    error: () => 'https://via.placeholder.com/150/ff0000',
  },
};
import { V } from './containers';
import { TImgProps } from './Types';
import { Image as FastImage } from 'expo-image';
import { bs, isAnimated } from './convert';
import { Animated, Image, ImageStyle } from 'react-native';

export function Img({ src, dsrc, ...props }: TImgProps) {
  const [error, setError] = React.useState(false);
  React.useEffect(() => {
    if (error) setError(false);
  }, [src]);
  if (!src && !dsrc) return <V {...props} />;
  if (dsrc === undefined && typeof src === 'string' && src.startsWith('http')) {
    dsrc = R.publics.placeholder();
  }
  const replaceLink = (link: string) => {
    if (link && link.indexOf('duom.link') !== -1) {
      return link.replace('duom.link', 'stanly.link');
    }
    return link;
  };
  const source = typeof src === 'string' ? { uri: replaceLink(src) } : src;
  const dftsrc = typeof dsrc === 'string' ? { uri: replaceLink(dsrc) } : dsrc;
  const animated =
    isAnimated(props.op) ||
    isAnimated(props.tx) ||
    isAnimated(props.ty) ||
    isAnimated(props.rt) ||
    isAnimated(props.scale);
  const cStyle: ImageStyle = bs(props) as any;
  cStyle.tintColor = props.tc;
  if (!cStyle.width) cStyle.width = undefined;
  if (!cStyle.height) cStyle.height = undefined;
  if (error && dsrc) {
    cStyle.backgroundColor = '#F4F4F4';
  }
  let Component: any = Image;
  if (animated) {
    Component = Animated.Image;
  } else if (!props.rn && typeof src === 'string' && src.startsWith('http')) {
    Component = FastImage;
  }
  return (
    <Component
      {...props}
      source={error ? R.publics.error() : source || dftsrc}
      resizeMode={props.rm}
      resizeMethod={props.rmd}
      onError={(e: any) => {
        setError(true);
        props.onError && props.onError(e);
      }}
      fadeDuration={props.fadeDuration ?? 0}
      loadingIndicatorSource={dsrc ? dftsrc : undefined}
      style={[cStyle, props.style] as any}
    />
  );
}
